// 主应用脚本 - 初始化和连接所有模块，处理应用逻辑

class RealtimeMonitoringApp {
    constructor() {
        this.isInitialized = false;
        this.isRunning = false;
        this.loadingProgress = 0;
        this.loadingSteps = ['config', 'core', 'modules', 'ui', 'data'];
        this.currentStep = 0;
    }

    // 初始化应用
    async init() {
        console.log('开始初始化实时数据监控系统...');
        
        // 显示加载界面
        this.showLoadingScreen();
        
        try {
            // 按顺序初始化各个部分
            await this.initializeConfig();
            await this.initializeCoreModules();
            await this.initializeUI();
            await this.initializeDataStreams();
            
            this.isInitialized = true;
            this.isRunning = true;
            
            console.log('实时数据监控系统初始化完成!');
            this.hideLoadingScreen();
            this.showWelcomeNotification();
            
        } catch (error) {
            console.error('初始化过程中发生错误:', error);
            this.showErrorScreen(error);
        }
    }

    // 初始化配置
    async initializeConfig() {
        this.updateLoadingProgress('加载系统配置...');
        
        // 确保realTimeSystem全局对象已创建
        if (!window.realTimeSystem) {
            window.realTimeSystem = {
                config: {},
                modules: {},
                utils: {},
                registerModule: function(name, module) {
                    this.modules[name] = module;
                    console.log(`模块已注册: ${name}`);
                }
            };
        }
        
        // 配置默认值
        realTimeSystem.config = {
            updateInterval: 1000, // 1秒更新间隔
            maxDataPoints: 1000,  // 每个数据源最大数据点数
            debugMode: false,     // 调试模式
            theme: 'light',       // 默认主题
            autoRefresh: true,    // 自动刷新
            alertsEnabled: true,  // 启用告警
            notificationsEnabled: true // 启用通知
        };
        
        // 合并本地存储的配置
        this.loadConfigFromStorage();
        
        // 初始化工具函数
        this.initializeUtils();
        
        this.updateLoadingProgress('系统配置加载完成');
        return Promise.resolve();
    }

    // 初始化工具函数
    initializeUtils() {
        realTimeSystem.utils = {
            // 格式化数字
            formatNumber: function(value, decimals = 2) {
                if (typeof value !== 'number') return value;
                return value.toFixed(decimals);
            },
            
            // 格式化时间戳
            formatTimestamp: function(timestamp, format = 'datetime') {
                const date = new Date(timestamp);
                
                switch (format) {
                    case 'time':
                        return date.toLocaleTimeString();
                    case 'date':
                        return date.toLocaleDateString();
                    case 'datetime':
                    default:
                        return date.toLocaleString();
                }
            },
            
            // 计算变化率
            calculateChangePercent: function(current, previous) {
                if (!previous || previous === 0) return 0;
                return ((current - previous) / previous) * 100;
            },
            
            // 节流函数
            throttle: function(func, delay) {
                let lastCall = 0;
                return function(...args) {
                    const now = Date.now();
                    if (now - lastCall >= delay) {
                        lastCall = now;
                        return func.apply(this, args);
                    }
                };
            },
            
            // 防抖函数
            debounce: function(func, delay) {
                let timeout;
                return function(...args) {
                    clearTimeout(timeout);
                    timeout = setTimeout(() => func.apply(this, args), delay);
                };
            },
            
            // 生成唯一ID
            generateId: function(prefix = 'id') {
                return `${prefix}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
            },
            
            // 深拷贝对象
            deepClone: function(obj) {
                if (obj === null || typeof obj !== 'object') return obj;
                if (obj instanceof Date) return new Date(obj.getTime());
                if (obj instanceof Array) return obj.map(item => this.deepClone(item));
                
                const clonedObj = {};
                for (const key in obj) {
                    if (obj.hasOwnProperty(key)) {
                        clonedObj[key] = this.deepClone(obj[key]);
                    }
                }
                
                return clonedObj;
            }
        };
    }

    // 从本地存储加载配置
    loadConfigFromStorage() {
        try {
            const storedConfig = localStorage.getItem('realtime_system_config');
            if (storedConfig) {
                const parsedConfig = JSON.parse(storedConfig);
                realTimeSystem.config = { ...realTimeSystem.config, ...parsedConfig };
                console.log('已加载本地存储的配置');
            }
        } catch (error) {
            console.warn('加载配置时出错:', error);
        }
    }

    // 保存配置到本地存储
    saveConfigToStorage() {
        try {
            localStorage.setItem('realtime_system_config', JSON.stringify(realTimeSystem.config));
            return true;
        } catch (error) {
            console.warn('保存配置时出错:', error);
            return false;
        }
    }

    // 初始化核心模块
    async initializeCoreModules() {
        this.updateLoadingProgress('初始化核心模块...');
        
        const modules = [
            { name: 'system', path: '/assets/js/system.js' },
            { name: 'dataStream', path: '/assets/js/data-engine.js' },
            { name: 'alertEngine', path: '/assets/js/alert-engine.js' },
            { name: 'historyPlayback', path: '/assets/js/history-playback.js' },
            { name: 'multiDashboard', path: '/assets/js/multi-dashboard.js' },
            { name: 'notificationCenter', path: '/assets/js/notification-center.js' },
            { name: 'webSocketClient', path: '/assets/js/websocket-client.js' }
        ];
        
        // 按顺序加载模块
        for (const module of modules) {
            try {
                // 检查模块是否已经加载
                if (realTimeSystem.modules[module.name]) {
                    this.updateLoadingProgress(`模块 ${module.name} 已加载，正在初始化...`);
                    // 调用模块的初始化方法
                    if (typeof realTimeSystem.modules[module.name].init === 'function') {
                        realTimeSystem.modules[module.name].init();
                    }
                } else {
                    console.warn(`模块 ${module.name} 未找到，将跳过初始化`);
                }
            } catch (error) {
                console.error(`初始化模块 ${module.name} 时出错:`, error);
            }
        }
        
        this.updateLoadingProgress('核心模块初始化完成');
        return Promise.resolve();
    }

    // 初始化UI
    async initializeUI() {
        this.updateLoadingProgress('初始化用户界面...');
        
        // 等待DOM加载完成
        if (document.readyState !== 'complete') {
            await new Promise(resolve => window.addEventListener('load', resolve));
        }
        
        // 初始化主题
        this.initializeTheme();
        
        // 初始化侧边栏
        this.initializeSidebar();
        
        // 初始化控制面板
        this.initializeControlPanel();
        
        // 初始化设置面板
        this.initializeSettingsPanel();
        
        // 初始化仪表盘
        if (realTimeSystem.modules.multiDashboard) {
            realTimeSystem.modules.multiDashboard.renderActiveDashboard();
        }
        
        // 添加窗口事件监听
        this.addWindowEventListeners();
        
        this.updateLoadingProgress('用户界面初始化完成');
        return Promise.resolve();
    }

    // 初始化主题
    initializeTheme() {
        const savedTheme = realTimeSystem.config.theme || 'light';
        document.body.setAttribute('data-theme', savedTheme);
    }

    // 初始化侧边栏
    initializeSidebar() {
        const sidebarToggle = document.querySelector('.sidebar-toggle');
        const sidebar = document.querySelector('.sidebar');
        
        if (sidebarToggle && sidebar) {
            sidebarToggle.addEventListener('click', () => {
                sidebar.classList.toggle('collapsed');
                document.querySelector('.main-content').classList.toggle('sidebar-collapsed');
            });
        }
        
        // 设置仪表盘导航
        this.setupDashboardNavigation();
    }

    // 设置仪表盘导航
    setupDashboardNavigation() {
        const dashboardNav = document.querySelector('.sidebar-nav.dashboards');
        if (!dashboardNav || !realTimeSystem.modules.multiDashboard) return;
        
        // 清空现有导航
        dashboardNav.innerHTML = '';
        
        // 添加仪表盘导航项
        const dashboards = realTimeSystem.modules.multiDashboard.getDashboards();
        dashboards.forEach(dashboard => {
            const navItem = document.createElement('li');
            navItem.className = `nav-item ${dashboard.id === realTimeSystem.modules.multiDashboard.activeDashboardId ? 'active' : ''}`;
            navItem.innerHTML = `
                <a href="#" class="nav-link" data-dashboard="${dashboard.id}">
                    <i class="material-icons">${dashboard.icon}</i>
                    <span>${dashboard.name}</span>
                </a>
            `;
            
            navItem.querySelector('a').addEventListener('click', (e) => {
                e.preventDefault();
                realTimeSystem.modules.multiDashboard.setActiveDashboard(dashboard.id);
                
                // 更新活动状态
                document.querySelectorAll('.sidebar-nav.dashboards .nav-item').forEach(item => {
                    item.classList.remove('active');
                });
                navItem.classList.add('active');
            });
            
            dashboardNav.appendChild(navItem);
        });
    }

    // 初始化控制面板
    initializeControlPanel() {
        // 初始化历史回放控制面板
        this.initializePlaybackControls();
        
        // 初始化刷新按钮
        const refreshBtn = document.querySelector('.control-btn.refresh');
        if (refreshBtn) {
            refreshBtn.addEventListener('click', () => {
                if (realTimeSystem.modules.multiDashboard) {
                    realTimeSystem.modules.multiDashboard.renderActiveDashboard();
                }
                
                // 显示刷新成功通知
                if (realTimeSystem.modules.notificationCenter) {
                    realTimeSystem.modules.notificationCenter.sendSystemNotification('success', '仪表盘已刷新');
                }
            });
        }
        
        // 初始化全屏按钮
        const fullscreenBtn = document.querySelector('.control-btn.fullscreen');
        if (fullscreenBtn) {
            fullscreenBtn.addEventListener('click', () => {
                if (!document.fullscreenElement) {
                    document.documentElement.requestFullscreen().catch(err => {
                        console.error(`全屏请求错误: ${err.message}`);
                    });
                } else {
                    if (document.exitFullscreen) {
                        document.exitFullscreen();
                    }
                }
            });
        }
    }

    // 初始化历史回放控制面板
    initializePlaybackControls() {
        if (!realTimeSystem.modules.historyPlayback) return;
        
        const playbackControls = document.getElementById('playback-controls');
        if (!playbackControls) return;
        
        // 播放按钮
        const playBtn = playbackControls.querySelector('.play-btn');
        if (playBtn) {
            playBtn.addEventListener('click', () => {
                const playback = realTimeSystem.modules.historyPlayback;
                if (!playback.isPlaying) {
                    playback.startPlayback();
                    playBtn.innerHTML = '<i class="material-icons">pause</i>';
                } else {
                    playback.pausePlayback();
                    playBtn.innerHTML = '<i class="material-icons">play_arrow</i>';
                }
            });
        }
        
        // 停止按钮
        const stopBtn = playbackControls.querySelector('.stop-btn');
        if (stopBtn) {
            stopBtn.addEventListener('click', () => {
                const playback = realTimeSystem.modules.historyPlayback;
                playback.stopPlayback();
                
                if (playBtn) {
                    playBtn.innerHTML = '<i class="material-icons">play_arrow</i>';
                }
            });
        }
        
        // 记录按钮
        const recordBtn = playbackControls.querySelector('.record-btn');
        if (recordBtn) {
            recordBtn.addEventListener('click', () => {
                const playback = realTimeSystem.modules.historyPlayback;
                if (!playback.isRecording) {
                    playback.startRecording();
                    recordBtn.classList.add('recording');
                } else {
                    playback.stopRecording();
                    recordBtn.classList.remove('recording');
                }
            });
        }
        
        // 速度控制
        const speedControl = playbackControls.querySelector('.speed-control');
        if (speedControl) {
            speedControl.addEventListener('change', () => {
                const playback = realTimeSystem.modules.historyPlayback;
                const speed = parseFloat(speedControl.value);
                playback.setPlaybackSpeed(speed);
            });
        }
    }

    // 初始化设置面板
    initializeSettingsPanel() {
        const settingsBtn = document.querySelector('.settings-btn');
        const settingsPanel = document.getElementById('settings-panel');
        
        if (settingsBtn && settingsPanel) {
            settingsBtn.addEventListener('click', () => {
                settingsPanel.classList.toggle('visible');
            });
            
            // 点击面板外部关闭面板
            document.addEventListener('click', (e) => {
                if (!settingsBtn.contains(e.target) && 
                    !settingsPanel.contains(e.target)) {
                    settingsPanel.classList.remove('visible');
                }
            });
        }
        
        // 初始化主题切换
        this.initializeThemeToggle();
    }

    // 初始化主题切换
    initializeThemeToggle() {
        const themeToggle = document.getElementById('theme-toggle');
        if (!themeToggle) return;
        
        // 设置初始状态
        themeToggle.checked = realTimeSystem.config.theme === 'dark';
        
        // 添加切换事件
        themeToggle.addEventListener('change', () => {
            const newTheme = themeToggle.checked ? 'dark' : 'light';
            realTimeSystem.config.theme = newTheme;
            document.body.setAttribute('data-theme', newTheme);
            this.saveConfigToStorage();
        });
    }

    // 添加窗口事件监听
    addWindowEventListeners() {
        // 窗口大小变化时重新渲染图表
        window.addEventListener('resize', realTimeSystem.utils.throttle(() => {
            if (realTimeSystem.modules.multiDashboard) {
                realTimeSystem.modules.multiDashboard.renderActiveDashboard();
            }
        }, 250));
        
        // 页面关闭前确认
        window.addEventListener('beforeunload', (e) => {
            // 如果正在记录或播放，提示用户
            const playback = realTimeSystem.modules.historyPlayback;
            if (playback && (playback.isRecording || playback.isPlaying)) {
                const message = '您有正在进行的操作，确定要离开吗？';
                e.returnValue = message;
                return message;
            }
        });
    }

    // 初始化数据流
    async initializeDataStreams() {
        this.updateLoadingProgress('初始化数据流...');
        
        // 初始化WebSocket连接
        if (realTimeSystem.modules.webSocketClient) {
            try {
                // 连接到模拟WebSocket服务
                await realTimeSystem.modules.webSocketClient.connect();
                
                // 订阅需要的数据频道
                realTimeSystem.modules.webSocketClient.subscribe('system');
                realTimeSystem.modules.webSocketClient.subscribe('finance');
                realTimeSystem.modules.webSocketClient.subscribe('iot');
                realTimeSystem.modules.webSocketClient.subscribe('alerts');
                
                console.log('WebSocket连接和数据订阅已完成');
            } catch (error) {
                console.warn('WebSocket连接失败，将使用模拟数据:', error);
                
                // 如果连接失败，启动模拟数据生成
                this.startMockDataGeneration();
            }
        } else {
            // 如果没有WebSocket客户端模块，启动模拟数据生成
            this.startMockDataGeneration();
        }
        
        this.updateLoadingProgress('数据流初始化完成');
        return Promise.resolve();
    }

    // 启动模拟数据生成
    startMockDataGeneration() {
        if (!realTimeSystem.modules.dataStream) return;
        
        const dataStream = realTimeSystem.modules.dataStream;
        const interval = realTimeSystem.config.updateInterval || 1000;
        
        console.log(`开始生成模拟数据，更新间隔: ${interval}ms`);
        
        // 系统数据模拟
        setInterval(() => {
            const systemData = {
                timestamp: Date.now(),
                cpu: 30 + Math.random() * 60, // 30%-90%
                memory: 40 + Math.random() * 50, // 40%-90%
                disk: 10 + Math.random() * 30, // 10%-40%
                network: {
                    in: Math.random() * 1000, // kb/s
                    out: Math.random() * 500 // kb/s
                },
                uptime: Date.now() - performance.timing.navigationStart
            };
            
            dataStream.addDataPoint('system', systemData);
        }, interval);
        
        // 金融数据模拟
        setInterval(() => {
            const symbols = ['AAPL', 'MSFT', 'GOOGL', 'AMZN'];
            const symbol = symbols[Math.floor(Math.random() * symbols.length)];
            
            const basePrice = {
                'AAPL': 150,
                'MSFT': 300,
                'GOOGL': 2800,
                'AMZN': 3200
            }[symbol];
            
            const priceChange = (Math.random() - 0.5) * basePrice * 0.02; // ±2%的波动
            const newPrice = basePrice + priceChange;
            const priceChangePercent = (priceChange / basePrice) * 100;
            
            const financeData = {
                timestamp: Date.now(),
                symbol,
                price: newPrice,
                priceChange: priceChange,
                priceChangePercent: priceChangePercent,
                volume: Math.floor(Math.random() * 100000) + 10000,
                volumeChangePercent: (Math.random() - 0.5) * 100
            };
            
            dataStream.addDataPoint('finance', financeData);
        }, interval);
        
        // IoT设备数据模拟
        setInterval(() => {
            const deviceCount = 5;
            const deviceId = `device_${Math.floor(Math.random() * deviceCount) + 1}`;
            
            const iotData = {
                timestamp: Date.now(),
                deviceId,
                status: Math.random() > 0.05 ? 'online' : 'offline', // 95%概率在线
                temperature: 20 + Math.random() * 50, // 20°C-70°C
                humidity: 30 + Math.random() * 50, // 30%-80%
                pressure: 980 + Math.random() * 40, // 980-1020 hPa
                batteryLevel: Math.random() * 100, // 0-100%
                signalStrength: Math.random() * 5 + 1 // 1-5格信号
            };
            
            dataStream.addDataPoint('iot', iotData);
        }, interval / 2); // IoT数据更新频率更高
    }

    // 显示加载界面
    showLoadingScreen() {
        const loadingScreen = document.createElement('div');
        loadingScreen.id = 'loading-screen';
        loadingScreen.className = 'loading-screen';
        loadingScreen.innerHTML = `
            <div class="loading-content">
                <div class="loading-logo">
                    <i class="material-icons">dashboard</i>
                </div>
                <h1>实时数据监控系统</h1>
                <div class="loading-progress">
                    <div class="progress-bar">
                        <div class="progress-fill" style="width: 0%"></div>
                    </div>
                    <p class="progress-text">正在初始化...</p>
                </div>
            </div>
        `;
        
        document.body.appendChild(loadingScreen);
    }

    // 更新加载进度
    updateLoadingProgress(message) {
        this.currentStep++;
        this.loadingProgress = (this.currentStep / this.loadingSteps.length) * 100;
        
        const progressFill = document.querySelector('#loading-screen .progress-fill');
        const progressText = document.querySelector('#loading-screen .progress-text');
        
        if (progressFill) {
            progressFill.style.width = `${this.loadingProgress}%`;
        }
        
        if (progressText && message) {
            progressText.textContent = message;
        }
    }

    // 隐藏加载界面
    hideLoadingScreen() {
        const loadingScreen = document.getElementById('loading-screen');
        if (loadingScreen) {
            loadingScreen.classList.add('fade-out');
            setTimeout(() => {
                document.body.removeChild(loadingScreen);
            }, 500);
        }
    }

    // 显示错误界面
    showErrorScreen(error) {
        const loadingScreen = document.getElementById('loading-screen');
        if (loadingScreen) {
            loadingScreen.innerHTML = `
                <div class="error-content">
                    <div class="error-icon">
                        <i class="material-icons">error_outline</i>
                    </div>
                    <h2>初始化失败</h2>
                    <p>${error.message || '系统初始化过程中发生错误'}</p>
                    <button class="retry-btn">重试</button>
                </div>
            `;
            
            const retryBtn = loadingScreen.querySelector('.retry-btn');
            if (retryBtn) {
                retryBtn.addEventListener('click', () => {
                    location.reload();
                });
            }
        }
    }

    // 显示欢迎通知
    showWelcomeNotification() {
        if (realTimeSystem.modules.notificationCenter) {
            realTimeSystem.modules.notificationCenter.sendSystemNotification('info', '欢迎使用实时数据监控系统', {
                duration: 5000
            });
        }
    }

    // 停止应用
    stop() {
        if (!this.isRunning) return;
        
        console.log('正在停止实时数据监控系统...');
        
        // 停止所有模块
        Object.values(realTimeSystem.modules).forEach(module => {
            if (typeof module.stop === 'function') {
                try {
                    module.stop();
                } catch (error) {
                    console.error('停止模块时出错:', error);
                }
            }
        });
        
        this.isRunning = false;
        console.log('实时数据监控系统已停止');
    }
}

// 当DOM加载完成时初始化应用
window.addEventListener('DOMContentLoaded', () => {
    // 创建并初始化应用
    window.app = new RealtimeMonitoringApp();
    
    // 延迟一点时间初始化，确保所有模块都已加载
    setTimeout(() => {
        window.app.init();
    }, 100);
});